<template>
   <div>
      <div class="handle-container">
         <s-button type="default" class="gap" @click="handleClearLogs">清除日志</s-button>
         <s-button type="default" class="gap" @click="handleExportLogs">导出日志</s-button>
         <s-button type="default" class="gap" @click="handleGetLogs(1)">刷新日志</s-button>
         <span>
            DEBUG：<s-checkbox
               :checked="Boolean(state.debug)"
               name="debug"
               style="display: inline-block"
               @update="handleDebug"
            />
         </span>
      </div>
      <div class="table-wrap" style="height: 500px;overflow: auto;" ref="tableRef">
         <table style="width: 100%;">
            <tr class="table-header">
               <td style="width: 50px;">序号</td>
               <td>内容</td>
            </tr>
            <tr v-for="(item,i) in state.logs" :key="item.index" :class="[{'hightlight':i===state.logs.length-1}]">
               <td>{{item.index}}</td>
               <td>{{item.content}}</td>
            </tr>
         </table>
      </div>
   </div>
</template>

<script lang="ts" setup>
import { BaseForm } from "@types"
import { onBeforeMount, reactive, ref, nextTick } from "vue"
import { SButton, SCheckbox, Message } from "@/components"
import { getLogs, clearLogs, exportLogs, debugLogs } from "@/request"
import { download } from "@/utils"
const tableRef = ref(null) // 表格dom
const state = reactive({
   logs: [],
   debug: 0
})

// 获取日志
const handleGetLogs = (refresh) => {
   getLogs().then((data) => {
      state.logs = data.loglist.filter(item => item.content !== "")
      state.debug = data.debug
      nextTick(() => {
         const el = tableRef.value
         console.log(el)
         el.scrollTop = el.scrollHeight
      })
      if(refresh){
         Message.success('操作成功！')
      }
   })
}

// 清空日志
const handleClearLogs = () => {
   clearLogs().then((res) => {
      Message.success("已清空")
      handleGetLogs()
   })
}

// 导出日志
const handleExportLogs = () => {
   exportLogs().then(data => {
      const uri = data.uri as string
      const fileName = uri.slice(uri.lastIndexOf("/") + 1)
      download(uri, fileName)
   })
}

// debug
const handleDebug = (params:BaseForm) => {
   debugLogs({
      debug: Number(params.value)
   }).then(res => {
      res && Message.success("操作成功")
   })
}

onBeforeMount(() => {
   handleGetLogs()
})

</script>

<style scoped lang="less">
   .handle-container {
      margin-bottom: @itemSpace;
      .gap {
         margin-right: 8px;
      }
   }
   table{
      .table-header{
         background-color: @default;
      }
      tr{
         &.hightlight{
            background-color: @success;
         }
         td{
         padding: 8px;
      }
      }
   }
</style>
